(function () {
    let template = function (self) {
        return `<aux-view class="mask"></aux-view><div class="image"></div><img src="">`
    };

    function onImageLoaded(self) {
        return function (e) {
            let naturalSize = window.aui.getNaturalSize(self.$ele.img);
            if (!self.classList.contains("loaded")) {
                self.classList.add("loaded");
                self.loaded = true;
            }
            self.$ele.lay.style.backgroundImage = `url(${self.$src})`;
            self.dispatchEvent(new CustomEvent("myload", {
                detail: naturalSize
            }));
        }
    }

    function onImageError(self) {
        return function (e) {
            self.dispatchEvent(new CustomEvent("myerror", {
                detail: {
                    errMsg: e.message
                }
            }));
        }
    }                

    function onNewValue(self, newval) {
        self.$src = newval;
        self.classList.remove("loaded");
        setTimeout(function () {
            self.$ele.img.src = newval;
            self.loaded = false;
        }, 0)
    }

    document.auiDefineElement(
        'aux-image',
        {
            template,
            props: {                
                src: {
                    afterCreated(self, newval) {
                        onNewValue(self, newval);
                    },
                    observer(self, oldval, newval) {
                        onNewValue(self, newval);
                    }
                }
            },
            created(self) {
                self.loaded = false;
                self.$onImageLoaded = onImageLoaded(self);
                self.$onImageError = onImageError(self);
                self.$ele.lay = self.children[1];
                self.$ele.img = self.children[2];
            },
            attached(self) {
                self.$ele.img.addEventListener("load", self.$onImageLoaded);
                self.$ele.img.addEventListener("error", self.$onImageError);
            },
            attrChanged(self, name, oldval, newval) {                    
            }
        }
    );
})();

